<template>
  <div>
    <div class="timeGroup">
      <a-radio-group v-model:value="timeSelected" @change="timeOptionChange">
        <a-radio-button
          v-for="(item, index) in timeOptionSchema"
          :key="index"
          :value="item"
        >
          <p v-if="item !== 1">近{{ item }}天</p>
          <p v-else>今天</p>
        </a-radio-button>
      </a-radio-group>
      <a-range-picker
        :format="format"
        v-model:value="timeValue"
        @change="timePickerChange"
        style="margin-left: 15px; width: 280px"
      >
        <template #suffixIcon>
          <SmileOutlined />
        </template>
      </a-range-picker>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, watch } from "vue";
import { millis2str } from "/@/utils/dateUtil";
import moment from "moment";
export default defineComponent({
  emits: ["register", "change"],
  setup(_, { emit }) {
    const timeSelected = ref();
    const timeValue = ref(moment(""));
    const format = ref("YYYY-MM-DD");
    const timeOptionChange = (e: any) => {
      setToolbarIndex(e.target.value);
    };
    const timeOptionSchema: any = ref();
    function setToolbarIndex(index: number) {
      timeSelected.value = index;
      const currentTimeMillis = new Date().getTime();
      let startTimeMillis: number = 0;
      const indexs = timeOptionSchema.value?.findIndex((val: any) => {
        return val === index;
      });
      startTimeMillis =
        currentTimeMillis -
        24 * 60 * 60 * 1000 * timeOptionSchema.value[indexs];
      setInputTimes(startTimeMillis, currentTimeMillis);
    }

    function setInputTimes(start: number, end: number) {
      let timeArr: any = [];
      timeArr.push(moment(millis2str(start)));
      timeArr.push(moment(millis2str(end)));
      timeValue.value = timeArr;
    }
    const timePickerChange = (_, value) => {
      timeValue.value = value;
    };
    function getInputTimes() {
      let timeArr: any = [];
      timeArr.push(new Date(timeValue.value[0]).getTime());
      timeArr.push(new Date(timeValue.value[1]).getTime());
      return timeArr;
    }
    emit("register", { getValue, setProps });
    watch(
      () => timeValue.value,
      () => {
        emit("change", getInputTimes());
      },
      { deep: true }
    );
    function setProps(val: any) {
      format.value = val.format;
      timeOptionSchema.value = val.options;
      setToolbarIndex(val.selectedOption);
    }
    function getValue() {
      return getInputTimes();
    }
    return {
      getInputTimes,
      timeOptionChange,
      timeSelected,
      timeValue,
      format,
      timeOptionSchema,
      timePickerChange,
    };
  },
});
</script>
